`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: Wuhan University 
// Engineer: Yu Zihao 
// 
// Create Date: 2021/08/10 18:26:53
// Design Name: 
// Module Name: lab7_top
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module lab7_top(clk,reset,SW,LEDR);
input clk,reset;
input [7:0] SW;   //SW   0x140
output [7:0] LEDR;//LEDR 0x100

wire [15:0] read_data;
wire [15:0] write_data;
wire [8:0] mem_addr;
wire [1:0] mem_cmd;//mem read or writ: MNONE,MREAD,MWRITE
wire msel,ram_write;
wire [15:0] ram_dout;

// RAM
//mem_cmd
//`define MNONE  2'00
//`define MREAD  2'01
//`define MWRITE 2'10
assign msel = ~mem_addr[8];
assign ram_write = mem_cmd[1] & msel;
wire tri_read_data = mem_cmd[0] & msel;
assign read_data = tri_read_data ? ram_dout : 16'bz;
RAM #(.filename("./sas/lab8fig4.txt"),
      .addr_width(8),
      .data_width(16)) ram_inst (
      .clk(clk),.read_address(mem_addr[7:0]),.write_address(mem_addr[7:0]),
      .write(ram_write),.din(write_data),.dout(ram_dout));
      
// memory mapped input and output devices
//SW   0x140
//LEDR 0x100
wire SWsel,LEDRsel;
assign SWsel   = mem_cmd[0] & (mem_addr == 9'h140); //9'd320
assign LEDRsel = mem_cmd[1] & (mem_addr == 9'h100); //9'd256
assign read_data = SWsel ? {8'b0,SW} : 16'bz;
VDFFE #(8) STATE(.clk(clk), .in(write_data[7:0]), .load(LEDRsel), .out(LEDR), .rst(reset));

cpu cpu_inst(.clk(clk),.reset(reset),.N(),.V(),.Z(),
           .mem_addr(mem_addr),.mem_cmd(mem_cmd),.read_data(read_data),.write_data(write_data));
           
endmodule
